package com.ruoyi.weixincp.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.weixincp.config.WxCpConfiguration;
import com.ruoyi.weixincp.service.IWeiXinCpService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessageSendResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WeiXinCpServiceImpl implements IWeiXinCpService {

    @Resource private WxCpConfiguration wxCpConfiguration;

    /**
     * 获取用户信息
     * @param userId
     * @return
     * @throws WxErrorException
     */
    @Override
    public WxCpUser getCpUserInfoById( String userId ) throws WxErrorException {
        WxCpUser userInfo = wxCpConfiguration.getWxCpService().getUserService( ).getById( userId );
        return userInfo;
    }

    /**
     * 获取所有的用户列表
     * @return
     * @throws WxErrorException
     */
    @Override
    public List<WxCpUser> getCpUserInfoList( ) throws WxErrorException {
        List<WxCpUser> list = new ArrayList( );
        try {
            // 获取用户列表
            List<WxCpDepart> deptList = wxCpConfiguration.getWxCpDepartmentService().list(  null);
//            List<WxCpDepart> deptList = wxCpDepartmentService.list( Long.valueOf( 100 ) );
            for ( WxCpDepart dept : deptList ) {
                // 处理获取到的部门信息
                List<WxCpUser> wxCpUsersList = wxCpConfiguration.getWxCpService().getUserService().listSimpleByDepartment( dept.getId( ), null, null );
                for ( WxCpUser wxCpUser : wxCpUsersList ) {
                    list.add( wxCpUser );
                }
            }
        } catch ( WxErrorException e ) {
            // 处理异常
            e.printStackTrace( );
        }
        return list;
    }


    /**
     * 获取部门列表
     * @return
     * @throws WxErrorException
     */
    @Override
    public List<WxCpDepart> getCpDeptList( ) throws WxErrorException {
        List<WxCpDepart> deptList = wxCpConfiguration.getWxCpDepartmentService().list( null);
        return deptList;
    }


    /**
     * 获取token
     * @return
     * @throws WxErrorException
     */
    @Override
    public String getToken( ) throws WxErrorException {
        return wxCpConfiguration.getWxCpService().getAccessToken();
    }


    /**
     * 企业微信应用消息推送
     * @param sendUrl  推送跳转连接
     * @param fillTime  推送时间
     * @param sendUserName 推送人姓名
     * @return
     * @throws WxErrorException
     */
    @Override
    public AjaxResult sendApplicationMessage( String sendUrl, String fillTime, String sendUserName ) throws ParseException, WxErrorException {

        Map<String,  Object> sendMap = new HashMap<>();
        List<String> failUserList = new ArrayList<>();
        List<String> successUserList = new ArrayList<>();
        String msg="";

        /*获取需要推送的人*/
        List<String>  userList=new ArrayList<>();
        userList.add( "LiKuiYing" );
//        userList.add( "FengYaSong" );
        if(userList.size() == 0){
            msg="没有配置发送人，请先配置后再发送";
            sendMap.put( "msg", msg);
            return new AjaxResult(500,msg,sendMap);
        }

        /**发送企业微信消息**/
        for ( String user : userList ) {
            WxCpMessageSendResult result=null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf_out = new SimpleDateFormat("yyyy年MM月");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            WxCpMessage message = new WxCpMessage();
            message.setAgentId(Integer.valueOf(1000002));
            message.setUrl(sendUrl);
            message.setToUser(user);
            message.setToParty("");
            message.setToTag("");
            message.setMsgType("textcard");
            message.setTitle("学习用 binarywang 4.6.0 集成企业微信");
            message.setBtnTxt("查看详情");
            String content="使用com.github.binarywang集成企业微信<br/>"
                    +"1、获取部门信息<br/>"
                    +"2、获取token信息<br/>"
                    +"4、发送消息<br/>"
                    +"5、获取部门人员<br/>";
            message.setDescription(
                    "<div class=\"gray\">学习日期：" + sdf_out.format( sdf.parse( fillTime ) ) + "</div>" +
                            "<div class=\"black\">学习内容：" +content  + "</div>" +
                            "<div class=\"gray\">学习人：" + sendUserName + "</div>" +
                            "<div class=\"gray\">发送时间：" + sdf1.format( new Date( ) ) + "</div>"
            );
            result = wxCpConfiguration.getWxCpMessageService().send( message );
            if (result.getErrCode() != 0) {
                failUserList.add( user );
            }else{
                successUserList.add( user );
            }
        }
        sendMap.put( "failUserList",failUserList );
        sendMap.put( "successUserList",successUserList );

        msg="发送成功";
        return new AjaxResult(200,msg,sendMap);
    }


}



